module.exports = (options, app) => {
  return async function apiLogger(ctx, next) {
    // let
    let logText = formatReqLog(ctx);
    let start = Date.now();
    ctx.logger.info(logText);
    await next();
    let resText = formatResLog(ctx, Date.now() - start, '');
    ctx.logger.info(resText);
  }
}



/**
 * 格式化请求日志
 * @param {any} ctx  全局上下文参数
 * @returns
 */
function formatReqLog(ctx) {
  const message = `\u001b[34m -------->>> ${ctx.method} \u001b[39m ${ctx.url} --IP: ${_getClientIp(ctx.request)}`

  let logText = new String();
  logText += "\n";
  // 请求信息
  logText += message + "\n";
  logText += `params: ${JSON.stringify(ctx.params)}\n`;
  logText += `query: ${JSON.stringify(ctx.query)}\n`;
  logText += `request.body: ${JSON.stringify(ctx.request.body)}\n`;
  // logText += `request.body: ${JSON.stringify(ctx)}\n`;
  return logText;
}


/**
 * 格式化响应日志
 * @param {any} ctx  全局上下文参数
 * @param {string} responseTime  响应时间
 * @param {Object} req  请求数据
 * @returns
 */
function formatResLog(ctx, responseTime, req) {
  const message = `\u001b[34m <<<<--------- ${ctx.method} \u001b[39m ${ctx.url} - \u001b[32m${responseTime}ms \u001b[39m`

  let logText = req;

  logText += "\n";
  // 响应信息
  logText += message + "\n";
  try {
    logText += JSON.stringify(ctx.body)
  } catch (error) {
    logText += ctx.body
  }

  logText += "\n";

  return logText;
}

function _getClientIp(req) {
  return req.headers['x-forwarded-for'] ||
    req.headers['X-Forwarded-For'] ||
    req.headers['X-Real-IP'] ||
    req.headers['Host'] ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
};